package com.uenpay.im.invokeitems.chat;

import android.content.Context;
import android.os.AsyncTask;

import com.qiyunxin.android.http.utils.StreamUtility;
import com.qyx.android.utilities.DateUtils;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.SendFileResult;

import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 上传文件
 * 
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class UploadMessageAttachment {
	OnAttachedListener _onAttachedListener;
	Context _context;

	/**
	 * 
	 * @param fileData
	 *            文件
	 * @param end
	 *            后缀名
	 * @param context
	 * 
	 * @param onAttachedListener
	 *            回调
	 */
	public UploadMessageAttachment(byte[] fileData, String end,
			Context context, OnAttachedListener onAttachedListener) {
		_context = context;
		_onAttachedListener = onAttachedListener;
		String url = APIConfiguration.getBaseUrl()
				+ "Chat/Chat/sendFile?"
				+ APIConfiguration.getCustIdAndToken();
		new FileUploadTask(url, end, fileData).execute();
	}

	private class FileUploadTask extends AsyncTask<Object, Integer, Void> {
		String _url;
		String _fileName;
		byte[] _fileData;
		boolean isFailed = true;

		public FileUploadTask(String url, String fileName, byte[] fileData) {
			_url = url;
			_fileName = fileName;
			_fileData = fileData;
		}

		SendFileResult sendResult = new SendFileResult();

		@Override
		protected Void doInBackground(Object... arg0) {
			HttpURLConnection conn;
			try {
				final String boundaryString = "--------------------------"
						+ java.util.UUID.randomUUID().toString();
				final String end = "\r\n";
				final String twoHyphens = "--";
				int statusCode = 0;
				URL uri = new URL(_url);
				conn = (HttpURLConnection) uri.openConnection();
				conn.setChunkedStreamingMode(1024 * 10);
				conn.setConnectTimeout(60 * 1000);
				conn.setDoInput(true);
				conn.setDoOutput(true);
				conn.setUseCaches(false);
				conn.setRequestMethod("POST");
				conn.setRequestProperty("Connection", "Keep-Alive");
				conn.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundaryString);

				StringBuilder sbHeader = new StringBuilder();
				sbHeader.append(end);
				sbHeader.append(twoHyphens);
				sbHeader.append(boundaryString);
				sbHeader.append(end);
				OutputStream dos = conn.getOutputStream();
				dos.write(sbHeader.toString().getBytes());

				dos.write(("Content-Disposition: form-data; name=\"uploadedFile\"; filename=\""
						+ DateUtils.getCurrentMills() + "." + _fileName + "\"")
						.getBytes());
				dos.write(end.getBytes());
				dos.write("Content-Type: application/octet-stream".getBytes());
				dos.write(end.getBytes());
				dos.write(end.getBytes());
				if (_fileData == null) {
					return null;
				}
				InputStream is = new ByteArrayInputStream(_fileData);
				byte[] buffer = new byte[1024];
				int count = 0;
				long total = 0;
				while ((count = is.read(buffer)) != -1) {
					total += count;
					publishProgress((int) (total * 100 / _fileData.length));
					dos.write(buffer, 0, count);
				}
				is.close();
				dos.write(end.getBytes());

				StringBuilder sbEnd = new StringBuilder();
				sbEnd.append(twoHyphens);
				sbEnd.append(boundaryString);
				sbEnd.append(twoHyphens);
				sbEnd.append(end);

				dos.write(sbEnd.toString().getBytes());
				dos.flush();

				statusCode = conn.getResponseCode();
				if (statusCode == HttpStatus.SC_OK) {
					isFailed = false;
					String result = StreamUtility.readStream(conn
							.getInputStream());

					JSONObject json = new JSONObject(result);
					sendResult.setStatus(json.optInt("status"));
					sendResult.setMsg(json.optString("msg"));
					JSONObject dataJson = json.optJSONObject("data");
					if (dataJson.has("filesize")) {
						String size = dataJson.optString("filesize");
						sendResult.setFileSize(size);
					}
					if (dataJson.has("filename")) {
						String size = dataJson.optString("filename");
						sendResult.setFileName(size);
					}
					if (dataJson.has("fileid")) {
						sendResult.setFileId(dataJson.optString("fileid"));
					}
					if (dataJson.has("filehash")) {
						sendResult.setFileHash(dataJson.optString("filehash"));
					}
					// ��ӷ��ص�URL��ַ
				} else {
					isFailed = true;
					StringBuilder sb = new StringBuilder();
					sb.append("Upload image failed. ");
					sb.append("The http response status code is ");
					sb.append(statusCode);
					sb.append(". The request url is ");
					sb.append(_url);
					// Log.e("FileUploadTask", sb.toString());
				}
				conn.disconnect();
			} catch (MalformedURLException e) {
				isFailed = true;
				// Log.e("FileUploadTask1", e.getMessage());
				// Logger.error("UploadTaskLogAttachment",
				// "MalformedURLException", e);
			} catch (JSONException e) {
				isFailed = true;
				// Log.e("FileUploadTask2", e.getMessage());
				// Logger.error("UploadTaskLogAttachment", "JSONException", e);
			} catch (IOException e) {
				isFailed = true;
				// Log.e("FileUploadTask3", e.getMessage());
				// Logger.error("UploadTaskLogAttachment",
				// "Upload attachment failed", e);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			_onAttachedListener.onAttached(sendResult, isFailed);
		}
	}
}
